<?php
/**
 * GumballMachine Class
 * 糖果机操作类
 *
 */

class GumballMachine {

    protected $soldOutState = null;
    protected $noCoinState  = null;
    protected $hasCoinState = null;
    protected $soldState    = null;

    public $state = null;
    public $count = 0;

    /**
     * Constructor.
     * @param   int     $num    number of gumball
     */
    public function __construct($num)
    {
        $this->soldOutState = new SoldOutState($this);
        $this->noCoinState  = new NoCoinState($this);
        $this->hasCoinState = new HasCoinState($this);
        $this->soldState    = new SoldState($this);

        $this->count = $num;
        if($num > 0)
            $this->state = $this->noCoinState;
        else
            $this->state = $this->soldOutState;
    }

    public function insertCoin()
    {
        $this->state->insertCoin();
    }

    public function ejectCoin()
    {
        $this->state->ejectCoin();
    }

    public function turnCrank()
    {
        $this->state->turnCrank();
        $this->state->dispense();
    }

    public function getState()
    {
        return $this->state;
    }

    public function setState($state)
    {
        $this->state = $state;
    }

    public function getNoCoinState()
    {
        return $this->noCoinState;
    }

    public function getHasCoinState()
    {
        return $this->hasCoinState;
    }

    public function getSoldOutState()
    {
        return $this->soldOutState;
    }

    public function getSoldState()
    {
        return $this->soldState;
    }

    public function releaseBall()
    {
        echo "A gumball comes rolling out the slot...\n";
        if($this->count != 0)
            $this->count--;
    }

    public function getCount()
    {
        return $this->count;
    }

    public function refill($num)
    {
        $this->count = $num;
        $this->state = $this->noCoinState;
    }

    public function show()
    {
        $str = sprintf("\nMighty Gumball , Inc.");
        $str .= sprintf("\nJava-enabled Standing Gumball Model #2004");
        $str .= sprintf("\nInventory: %d gumball", $this->count);
        if($this->count != 1)
            $str .= sprintf("s");
        $str .= sprintf("\n");
        $str .= sprintf("Machine is %s\n", get_class($this->state));

        return $str;
    }

}